package com.sxjh.controller.ny;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sxjh.common.BaseController;
import com.sxjh.common.Constant;
import com.sxjh.common.Result;
import com.sxjh.entity.*;
import com.sxjh.entity.param.UnloadLogWeighParam;
import com.sxjh.entity.result.TaskListResult;
import com.sxjh.entity.result.UnloadLogWeighResult;
import com.sxjh.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;


/**
 * <p>
 * 卸货记录  前端控制器
 * </p>
 *
 * @author zixin
 * @since 2021-06-06
 */
@Deprecated
@RestController
public class UnloadLog2Controller extends BaseController {

    @Autowired
    private IcService icService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private GoodsLocationService goodsLocationService;

    @Autowired
    private UnloadLogService unloadLogService;

    @Autowired
    private IcLogService icLogService;

    @Autowired
    private WagonNumberService wagonNumberService;

    @Autowired
    private FileService fileService;

    @ApiOperation("过磅")
    @PostMapping("/weigh")
    Result<UnloadLogWeighResult> weigh(@RequestBody @Validated UnloadLogWeighParam param) {
        TimeInterval timer = DateUtil.timer();
        TimeInterval timer1 = DateUtil.timer();
        logger.error("内部倒运过磅记录：{}，操作节点：开始，已用时间：{}", param.getIcNumber(), timer.intervalRestart());
        logger.error("过磅请求记录：{}", param);
        if (!NumberUtil.isNumber(param.getWeight())) return err("磅数不能为空");
        // 过空磅
        synchronized (icService) {
            Ic ic = icService.getOne(new LambdaQueryWrapper<Ic>().eq(Ic::getNumber, param.getIcNumber()));
            logger.error("内部倒运过磅记录：{}，操作节点：获取完IC卡号，已用时间：{}", param.getIcNumber(), timer.intervalRestart());
            if (ic == null) return err("IC卡卡号在系统中不存在");
            if (ic.getWagonNumberId() == null || ic.getWagonNumberId() == 0) err("IC卡未绑定车辆信息");
            WagonNumber wagonNumber = wagonNumberService.getById(ic.getWagonNumberId());
            logger.error("内部倒运过磅记录：{}，操作节点：获取完车号信息，已用时间：{}", param.getIcNumber(), timer.intervalRestart());
            if (wagonNumber == null) return err("车辆信息不存在");
            // 判断空磅还是重磅
            // 空磅，重复提交
            if (StrUtil.isNotEmpty("ic.getTare()")) {
                long diff = LocalDateTimeUtil.between(ic.getCreatedAt(), LocalDateTime.now(), ChronoUnit.MINUTES);
                if (diff < 5) return err("请勿重复进行空磅称重");
            } else {
                double tare = Convert.toDouble(wagonNumber.getTare());
                if (tare > Convert.toDouble(param.getWeight())) return err("空磅不能小于该车皮重下限");
                if ((Convert.toDouble(param.getWeight()) - tare) >= 5) return err("空磅重量异常，高于皮重下限5吨");
                // 空磅称重保存
                if (NumberUtil.isNumber(param.getWeight())) err("称重数据格式异常" + param.getWeight());
                //ic.setTare(param.getWeight());
                ic.setCreatedAt(LocalDateTime.now());
                //ic.setTareImg(param.getImg1());
                //ic.setTareImgTwo(param.getImg2());
                icLogService.saveLog(ic.getWagonNumberId(), param.getIcNumber()
                        , param.getWeight(), param.getImg1()
                        , param.getImg2(), Constant.UNLOAD_EMPTY);
                logger.error("内部倒运过磅记录：{}，操作节点：保存完操作日志，已用时间：{}", param.getIcNumber(), timer.intervalRestart());
                // 返回显示信息
                UnloadLogWeighResult result = new UnloadLogWeighResult();
                //result.setTare(param.getWeight());
                result.setVehNumber(wagonNumber.getNumber());
                boolean isU = icService.updateById(ic);
                logger.error("内部倒运过磅记录：{}，操作节点：提交空磅数据成功，已用时间：{}", param.getIcNumber(), timer.interval());
                logger.error("内部倒运过磅记录：{}，操作节点：提交空磅数据成功，总耗时：{}", param.getIcNumber(), timer1.interval());
                return isU ? cus(0, "提交空磅数据成功", result) : err("保存空磅数据出错");
            }
            // 过重磅
            synchronized (taskService) {
                // 该车任务
                Task task = taskService.getOne(
                        new LambdaQueryWrapper<Task>()
                                .eq(Task::getWagonNumberId, ic.getWagonNumberId()));
                logger.error("内部倒运过磅记录：{}，操作节点：获取完该车任务，已用时间：{}", param.getIcNumber(), timer.intervalRestart());
                if (task == null) err("没有该车对应的任务");
                // 该车装货点信息
                GoodsLocation goodsLocation = goodsLocationService.getOne(
                        new LambdaQueryWrapper<GoodsLocation>()
                                .eq(GoodsLocation::getId, task.getLoadId()));
                logger.error("内部倒运过磅记录：{}，操作节点：获取完装货点信息，已用时间：{}", param.getIcNumber(), timer.intervalRestart());
                // 查看最新的卸货记录
                synchronized (unloadLogService) {
                    // 查看该车的最新卸货记录
                    UnloadLog unloadLog = unloadLogService.getOne(
                            new LambdaQueryWrapper<UnloadLog>()
                                    .eq(UnloadLog::getWagonNumberId, ic.getWagonNumberId())
                                    .orderByDesc(UnloadLog::getCreatedAt), false);
                    logger.error("内部倒运过磅记录：{}，操作节点：获取完最新卸货记录，已用时间：{}", param.getIcNumber(), timer.intervalRestart());
                    if (unloadLog != null) {
                        LocalDateTime oldDate = unloadLog.getCreatedAt();
                        // 上一条记录距离当前日期时间
                        long diff = LocalDateTimeUtil.between(oldDate, LocalDateTime.now(), ChronoUnit.MINUTES);
                        // 2分钟内重复提交，返回打印信息
                        if (diff <= 3) {
                            Result<UnloadLogWeighResult> result = print(unloadLog.getNumber());
                            if (result.getCode() == 200) return cus(0, "已提交数据，正在补打地榜单", result.getData());
                            return result;
                        }
                        if (diff < goodsLocation.getIntervalTime()) return err("请勿重复提交重磅信息");
                    }
                    double capacity = Convert.toDouble(wagonNumber.getCapacity());
                    if (capacity < Convert.toDouble(param.getWeight())) return err("重磅不能大于该车载重");
                    if (Convert.toDouble("ic.getTare()") >= Convert.toDouble(param.getWeight()))
                        return err("异常：毛重小于皮重");
                    // 保存重磅信息
                    unloadLog = new UnloadLog();
                    unloadLog.setIcId(ic.getId());
                    unloadLog.setLoadId(task.getLoadId());
                    unloadLog.setUnloadId(task.getUnloadId());
                    unloadLog.setWagonNumberId(ic.getWagonNumberId());
                    unloadLog.setMaterialId(task.getMaterialId());
                    //unloadLog.setTare(ic.getTare());
                    unloadLog.setRough(param.getWeight());
                    unloadLog.setRoughImg(param.getImg1());
                    unloadLog.setRoughImgTwo(param.getImg2());
                    icLogService.saveLog(ic.getWagonNumberId(), param.getIcNumber()
                            , param.getWeight(), param.getImg1(), param.getImg2(), Constant.UNLOAD_WEIGHT);
                    logger.error("内部倒运过磅记录：{}，操作节点：保存完操作日志，已用时间：{}", param.getIcNumber(), timer.intervalRestart());
                    // 查询任务信息
                    TaskListResult taskListResult = taskService.list(wagonNumber.getId());
                    logger.error("内部倒运过磅记录：{}，操作节点：保存完操作日志，已用时间：{}", param.getIcNumber(), timer.intervalRestart());
                    // 返回显示信息
                    UnloadLogWeighResult result = new UnloadLogWeighResult();
                    //result.setTare(ic.getTare());
                    //result.setRough(param.getWeight());
                    result.setVehNumber(wagonNumber.getNumber());
                    //result.setNetWeight(NumberUtil.sub(param.getWeight(), ic.getTare()).toString());
                    result.setPrinting(ic.getPrinting());
                    result.setMaterialName(taskListResult.getMaterialName());
                    //result.setUnloadName(taskListResult.getUnloadName());
                    //result.setLoadName(taskListResult.getLoadName());
                    String number = unloadLogService.serial();
                    logger.error("内部倒运过磅记录：{}，操作节点：查询完流水号，已用时间：{}", param.getIcNumber(), timer.intervalRestart());
                    unloadLog.setNumber(number);
                    unloadLogService.save(unloadLog);
                    logger.error("内部倒运过磅记录：{}，操作节点：保存卸货记录结束，已用时间：{}", param.getIcNumber(), timer.interval());
                    logger.error("内部倒运过磅记录：{}，操作节点：保存卸货记录结束，总耗时：{}", param.getIcNumber(), timer1.interval());
                    //result.setWeighingTime(unloadLog.getCreatedAt());
                    //result.setNumber(number);
                    return cus(0, "提交重磅数据成功", result);
                }
            }
        }
    }

    @ApiOperation("过磅3(需要同时上传图片)")
    @PostMapping(value = "/weigh3", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file1", value = "文件上传", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "file2", value = "文件上传", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "weight", value = "磅数", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "icNumber", value = "ic卡编号", required = true, dataTypeClass = String.class)})
    Result<UnloadLogWeighResult> weigh3(@ApiParam(hidden = true) MultipartFile file1, @ApiParam(hidden = true) MultipartFile file2, String weight, String icNumber) {
        if (StrUtil.isEmpty(weight)) return err("磅数不能为空");
        if (StrUtil.isEmpty(icNumber)) return err("卡号不能为空");
        if (file1 == null) return err("图片1不能为空");
        if (file2 == null) return err("图片2不能为空");
//    if (files == null || files.length != 2) return err("请上传两张图片");
//    MultipartFile file1 = files[0];
//    MultipartFile file2 = files[1];
        String img1 = "";
        String img2 = "";
        try {
            img1 = fileService.saveFile(file1);
            img2 = fileService.saveFile(file2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StrUtil.isEmpty(img1) || StrUtil.isEmpty(img2)) err("上传图片失败请重试");
        UnloadLogWeighParam entity = new UnloadLogWeighParam();
        entity.setIcNumber(icNumber);
        entity.setWeight(weight);
        entity.setImg1(img1);
        entity.setImg2(img2);
        return weigh(entity);
    }

    @ApiOperation("打印地榜单")
    @GetMapping("/print/{number}")
    public Result<UnloadLogWeighResult> print(@PathVariable String number) {
        //unloadLogService.getPrint(number);
        return ok(null);
    }


}